/** @file:封装axios文件 */
import Qs from 'qs';
import md5 from 'js-md5';
import Vue from '../main';
import {
	customMessage
} from '@/util/utils';
import axios from 'axios';
import router from '../router/index';

const instance = axios.create();
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 添加请求拦截器
instance.interceptors.request.use(function(config) {
	config.data = {
		...config.data
	};
	let time = parseInt(new Date().getTime() / 1000);
	let user_id = localStorage.getItem('user_id') || '';
	let token = localStorage.getItem('token') || '';
	let sign = md5(user_id + token + time + md5('huankemao'));
	config.data.time = time;
	config.data.user_id = user_id;
	config.data.token = token;
	config.data.sign = sign;
	config.data = Qs.stringify(config.data);
	return config;
}, function(error) {
	// 对请求错误做些什么
	return Promise.reject(error);
});
// 添加响应拦截器
instance.interceptors.response.use(function(response) {
	switch (response.data.code) {
		case 200:
			return response.data;
		case 500:
			if (response.data.msg == '用户不存在') {
				localStorage.removeItem('token');
				localStorage.removeItem('user_id');
				localStorage.removeItem('phone');
				location.reload();
			} else {
				customMessage.error({
					message: response.data.msg
				})
				return Promise.reject(response.data);
			}
			case 501:
				localStorage.removeItem('token');
				localStorage.removeItem('user_id');
				localStorage.removeItem('phone');
				customMessage.error({
					message: response.data.msg
				});
				location.reload();
				return Promise.reject(response.data);
			case 502:
			case 503:
				customMessage.error({
					message: response.data.msg
				})
				return Promise.reject(response.data);
	}
}, function(error) {
	return Promise.reject(error);
});

export default instance;
